package com.whut.util;


import com.jcraft.jsch.*;
import com.whut.wesocket.PollWebSocketServlet;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by YY on 2018-01-21.
 */
public class JSchUtil {

    private static final Logger logger = Logger.getLogger(JSchUtil.class);
    private static final int DEFAULT_SSH_PORT = 22;

    private String ipAddress;
    private String username;
    private String password;
    private int port;
    public JSchUtil(final String ipAddress, final String username, final String password) {
        this.ipAddress = ipAddress;
        this.username = username;
        this.password = password;
        port=DEFAULT_SSH_PORT;
    }
    public JSchUtil(final String ipAddress, int port, final String username, final String password) {
        this.ipAddress = ipAddress;
        this.username = username;
        this.password = password;
        this.port=port;
    }
    // 执行命令
    public int execute(final String command) {
        int returnCode = 0;
        JSch jsch = new JSch();
        try {
            // 创建连接 session.
            Session session = jsch.getSession(username, ipAddress, port);
            session.setPassword(password);
            JSchUtil.MyUserInfo userInfo = new JSchUtil.MyUserInfo();
            session.setUserInfo(userInfo);
            session.connect();
            // 创建和连接 channel.
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader(channel
                    .getInputStream()));
            channel.connect();
            logger.info("输入的执行指令为：" + command);
            // 从远程控制台捕获输出
            String line;
            while ((line = input.readLine()) != null) {
                logger.info("远程：" + line);
            }
            input.close();
            // Get the return code only after the channel is closed.
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }
            // Disconnect the channel and session.
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }
    // 执行命令
    public int execute(final String command, String webSocketKey, PollWebSocketServlet webSocketServlet) {
        int returnCode = 0;
        JSch jsch = new JSch();
        JSchUtil.MyUserInfo userInfo = new JSchUtil.MyUserInfo();
        try {
            // 创建连接 session.
            Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);
            session.setPassword(password);
            session.setUserInfo(userInfo);
            session.connect();

            // 创建和连接 channel.
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader(channel
                    .getInputStream()));

            channel.connect();
            logger.info("输入的执行指令为：" + command);

            // 从远程控制台捕获输出
            String line;
            while ((line = input.readLine()) != null) {
                logger.info("远程：" + line);
                SendMessageUtil.sendMessage(webSocketKey, line, webSocketServlet);
            }
            input.close();
            // Get the return code only after the channel is closed.
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }
            // Disconnect the channel and session.
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }

    // 重写用户信息内部类
    public static class MyUserInfo implements UserInfo {
        private String password;
        private String passphrase;

        @Override
        public String getPassphrase() {
            System.out.println("用户信息：获取密码 ");
            return null;
        }

        @Override
        public String getPassword() {
            System.out.println("用户信息：得到密码 ");
            return null;
        }

        @Override
        public boolean promptPassphrase(final String arg0) {
            System.out.println("用户信息：提示密码 " + arg0);
            return false;
        }

        @Override
        public boolean promptPassword(final String arg0) {
            System.out.println("用户信息：提示密码 " + arg0);
            return false;
        }

        @Override
        public boolean promptYesNo(final String arg0) {
            System.out.println("用户信息：提示YesNo " + arg0);
            return arg0.contains("The authenticity of host");
        }

        @Override
        public void showMessage(final String arg0) {
            System.out.println("用户信息：显示消息 ");
        }
    }
}
